package chain_of_responsibility

import (
	"math"
)

const abortIndex = math.MaxInt8 / 2

type Middleware func(*Context) error

type Context struct {
	handlers []Middleware
	index    int8
}

func (c *Context) Use(middleware ...Middleware) {
	if len(c.handlers)+len(middleware) >= abortIndex {
		panic("too many handlers")
	}
	c.handlers = append(c.handlers, middleware...)
}

func (c *Context) Handle() error {
	for ; c.index < int8(len(c.handlers)); c.index++ {
		if err := c.handlers[c.index](c); err != nil {
			return err
		}
	}
	return nil
}

func (c *Context) Abort() {
	c.index = abortIndex
}
